<!-- 部门配置 -->
<template>
  <div class="dashboard-editor-container">
    <el-row style="background: #fff; padding: 16px 16px 0;">
      <div class="top topSubmitBtn">
        <el-button class="btn" type="primary" @click="addDepartment()">添加部门</el-button>
      </div>
      <div>
        <el-table stripe :data="tableData" style="width: 100%; margin: 15px 0" row-key="ID" default-expand-all
          :tree-props="{ children: 'children', hasChildren: 'hasChildren' }">
          <el-table-column prop="date" type="index" label="序号" width="80" align="left"></el-table-column>
          <el-table-column prop="DepartmentName" label="部门名称"></el-table-column>
          <el-table-column label="操作" align="left" width="80px">
            <template slot-scope="scope">
              <!-- <el-button size="mini" @click="handleEdit(scope.row)">修改</el-button> -->
              <el-button size="mini" type="danger" @click="handleDelete(scope.row)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>
    </el-row>
    <el-dialog :close-on-click-modal="false" :close-on-press-escape=false title="添加部门" :visible.sync="dialogVisible"
      v-el-drag-dialog width="calc(27% - 8px)">
      <el-form label-width="120px" :model="departForm" :rules="rules" ref="departForm">
        <el-divider content-position="left">基本信息</el-divider>
        <div class="rule-container">
          <!-- <div class="rule-content"> -->
          <el-form-item label='上级部门:'>
            <el-cascader :popper-class="color === 'night' ? 'nightClass' : ''" ref="cascaderAddr" style="width:100%;"
              v-model="departForm.lastDepartmemt" placeholder="请选择部门，若空则为根部门" clearable :show-all-levels="false"
              :options="options"
              :props="{ expandTrigger: 'hover', checkStrictly: true, label: 'DepartmentName', value: 'ID' }"
              @visible-change="elCascaderOnlick" @expand-change="elCascaderOnlick" @change="handleChange">
            </el-cascader>
          </el-form-item>
          <el-form-item label='部门名称:' prop="departName">
            <el-input v-model="departForm.departName" maxlength="16"></el-input>
          </el-form-item>
        </div>
      </el-form>
      <!--   分割线与dialog-footer的间距 -->
      <el-divider class="lineToFooter"></el-divider>

      <span slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submit()">确 定</el-button>
        <el-button type="info" @click="dialogVisible = false">取 消</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import { connrequest } from "@/api/firstPage";
import { treeing, getTreeData } from "@/utils/index.js";
import elDragDialog from '@/directive/el-drag-dialog' // base on element-ui
export default {
  directives: { elDragDialog },
  data() {
    return {
      color: '',
      dialogVisible: false,
      departForm: {},
      options: [],
      tableData: [],
      compare: [],
      mapping: [],
      rules: {
        departName: [
          { required: true, message: '部门名称不能为空' }
        ]
      }
    };
  },
  //生命周期 - 创建完成（访问当前this实例）
  created() {
    this.getData()
    this.getMapping()
  },
  //生命周期 - 挂载完成（访问DOM元素）
  mounted() {
    this.color = localStorage.getItem('isNightMode') || 'night'

  },
  methods: {
    async getData() {
      const res = await connrequest('GetDepartment')
      let arr = getTreeData(treeing(res.Data, 'ID', 'ParentID'))
      this.tableData = arr
      this.compare = res.Data
    },
    async getMapping() {
      //获取员工（终端用户）映射表
      const res = await connrequest('GetEmployee')
      this.mapping = res.Data
    },
    addDepartment() {
      this.departForm = { lastDepartmemt: this.tableData?.[0]?.ID }
      this.ParentID = this.tableData?.[0]?.ID
      this.ParentName = this.tableData?.[0]?.label
      this.options = this.tableData
      this.$nextTick(() => {
        this.$refs['departForm'].clearValidate()
      })
      this.dialogVisible = true
    },
    handleEdit(item) {
      this.$message.info('该功能还在开发中')
      return
      this.options = this.tableData
      this.$set(this.departForm, 'lastDepartmemt', item.ID)
      this.$set(this.departForm, 'departName', item.DepartmentName)
      this.dialogVisible = true
    },
    handleChange(item) {
      if (item) {
        this.ParentID = item[item.length - 1]
        this.ParentName = this.$refs['cascaderAddr'].getCheckedNodes()[0].label
      }
    },
    // 判断部门不能重复，但是子部门可以重复
    // isDuplicateDepartment(departmentName, parentId) {
    //   const children = this.tableData.filter(
    //     (department) => department.ParentID === parentId
    //   );
    //   if (
    //     children.some(
    //       (department) =>
    //         department.DepartmentName.toLowerCase() === departmentName.toLowerCase()
    //     )
    //   ) {
    //     return true; // 部门名称已存在
    //   }
    //   return false; // 部门名称不存在重复
    // },
    async submit() {
      this.$refs['departForm'].validate(async (valid) => {
        if (valid) {
          // const EmployeeRes = await connrequest('GetEmployee')
          // let hasEmployee = EmployeeRes.Data.findIndex(item => item.Department === this.ParentName)
          // console.log(this.ParentName);
          // if (hasEmployee !== -1) {
          //   this.$message.error(`${this.ParentName}下存在终端，请删除${this.ParentName}的所有终端后操作`);
          //   return false
          // }
          if (this.compare.find(item => item.DepartmentName === this.departForm.departName)) {
            this.$message.info("部门已经存在");
            return false
          }
          const data = {
            Data: {
              ID: 0,
              DepartmentName: this.departForm.departName,
              ParentID: this.ParentID,
              ParentName: this.ParentName
            }
          }
          const res = await connrequest('AddDepartment', data)
          if (res.Status.StatusCode === 0) {
            this.$message({
              type: 'success',
              message: '部门添加成功'
            });
            this.getData()
            this.dialogVisible = false
          }
        }
      })
    },
    async handleDelete(item) {
      if (this.compare.find(children => children.ParentName === item.DepartmentName)) {
        this.$message.error(`${item.DepartmentName}下存在子部门，请删除${item.DepartmentName}的所有子部门后操作`)
        return false
      }
      if (this.mapping.find(depart => depart.Department === item.DepartmentName)) {
        this.$message.error(`${item.DepartmentName}下存在终端，请删除${item.DepartmentName}的所有终端后操作`);
        return false
      }
      this.$confirm('此操作将永久删除该部门, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async () => {

        let data = {
          Data: {
            ParentID: 0,
            ID: item.ID,
            DepartmentName: item.DepartmentName
          }
        }
        const res = await connrequest('DelDepartment', data)
        if (res.Status.StatusCode === 0) {
          this.$message({
            type: 'success',
            message: '删除成功!'
          });
          this.getData()
          this.dialogVisible = false
        }
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        });
      });
    },
    findEmployeeByDepartment(employees, targetDepartment) {
      // 遍历数组
      for (let i = 0; i < employees.length; i++) {
        // 检查当前对象的 Department 是否与目标值相等
        if (employees[i].Department === targetDepartment) {
          console.log("无法删除！！！");
          return; // 如果匹配，返回整个对象
        }
      }
      console.log("进入标志");
    },
    elCascaderOnlick() {
      let that = this;
      setTimeout(function () {
        document.querySelectorAll(".el-cascader-node__label").forEach((el) => {
          el.onclick = function () {
            this.previousElementSibling.click();
            that.$refs.cascaderAddr.dropDownVisible = false;
          };
        });
      }, 100);
    }
  }

};
</script>
<style scoped lang='scss'>
/* @import url(); 引入css类 */
.top {
  display: flex;
  justify-content: space-between;
  align-items: center;
}
</style>
